from authkit.authenticate import middleware
from authkit.authenticate.digest import digest_password


class MethodDigestMiddleware(object):
    """
    A digest authentication middleware for specific methods.

    """
    def __init__(self, application, user, password, realm='webskine',
            allowed_methods=['GET', 'HEAD']):
        self.application = application
        self.allowed_methods = allowed_methods

        # Set authenticator.
        def digest(environ, realm, username):
            return digest_password(realm, user, password)

        self.authenticate = middleware(
                self.application,
                method='digest',
                realm=realm,
                users_digest=digest)
    
    def __call__(self, environ, start_response):
        method = environ['REQUEST_METHOD']
        if method in self.allowed_methods:
            return self.application(environ, start_response)
        else:
            return self.authenticate(environ, start_response)
